var AV = require('leanengine');
var async = require('async');
var config = require('../config.js');
var AddrM = require('../models/address');
var log4js = require('log4js');
var logger = log4js.getLogger('normal');
module.exports = {
    //新增地址&&修改地址
    saveAddress:function(req,res,next){
        var uid = req.AV.user.id;
        var addr = req.query;//获取表单参数
        //console.log(addr);
        addr['location']= new AV.GeoPoint({latitude: 39.9, longitude: 116.4});
        if(addr.isDefault=="true"){
            addr['isDefault']=true;
        }else if(addr.isDefault=="false"){
            addr['isDefault']=false;
        }else{
        }
        //console.log(addr);
        addr['uid']=uid;
        AddrM.saveAddress(addr).then(function(obj){
            //保存成功
            res.json(obj);
            logger.info(obj);
        }).catch(function(err){
            logger.error(err);
        });
    },
    //获取默认地址
    getDefaultAddress:function(req, res, next){
        var uid = req.AV.user.id;
        AddrM.getDefaultAddress(uid).then(function(obj){
            res.json(obj);
            logger.info(obj);
        }).catch(function(err){
            logger.error(err);
            res.json(err);
        });
    },
    listAddressUi:function(req, res, next){
        if(req.query.back){
            res.render('user/address',{title:'我的地址',backurl:req.query.back});
        }else{
            res.render('user/address',{title:'我的地址',backurl:""});
        }
    },
    listAddress:function(req, res, next){
        var uid = req.AV.user.id;
        AddrM.listAddress(uid).then(function(obj){
            res.json(obj);
            //logger.info(obj);
        }).catch(function(err){
            logger.error(err);
            res.json(err);
        });
    },
    deleteAddress:function(req, res){
        var objectId=req.query.objectId;
        AddrM.deleteAddress(objectId).then(function(obj){
            res.json(obj);
            logger.info(obj);
        }).catch(function(err){
            logger.error(err);
            res.json(err);
        });
    },
     setDefaultAddress:function(req, res){
         var uid=req.AV.user.id
         var objectId=req.query.objectId;
        AddrM.setDefaultAddress(objectId,uid).then(function(obj){
            res.json(obj);
            logger.info(obj);
        }).catch(function(err){
            logger.error(err);
            res.json(err);
        });
    },



};